package cn.learn.activiti.service.impl;

import cn.learn.activiti.domain.ActNodeConfig;
import cn.learn.activiti.domain.CurrentTaskVo;
import cn.learn.activiti.service.IDeploymentService;
import cn.learn.activiti.service.IProcessService;
import cn.learn.activiti.service.ITaskService;
import cn.learn.activiti.util.ActThreadLocalContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.*;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author huangyezhan
 * @version 1.0
 * @date 2021年03月11日18:02
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ProcessServiceImpl implements IProcessService {

    private final RuntimeService     runtimeService;
    private final IDeploymentService deploymentService;

    private final ITaskService taskService;

    @Override
    public CurrentTaskVo startProcess(String processKey, String businessKey, Map<String, Object> variables, ActNodeConfig actNodeConfig) {
        //BpmnModel   model = deploymentService.getBpmnModel("Process_1:1:bd29ea34-8338-11eb-9bf8-0c541597bb97");
        //Set<String> ids   = ActivitiUtils.getJuelElementIds2FirstTask(model);
        //获取下一节点的id，根据id获取参数和参数名称

        // 设置节点的配置信息
        try {
            ActThreadLocalContext.setActNodeConfig(actNodeConfig);

            Authentication.setAuthenticatedUserId("tom");
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, businessKey, variables);
            runtimeService.setProcessInstanceName(processInstance.getProcessInstanceId(), "实例名称==");

            System.out.println(processInstance.getId());

            //获取当前任务节点
            List<Task>  tasks = taskService.getTasksByBusinessKey(businessKey);
            Set<String> nodes = tasks.stream().map(Task::getTaskDefinitionKey).collect(Collectors.toSet());
            //获取到这些节点的条件线

            return new CurrentTaskVo()
                    .processDefinitionId(processInstance.getProcessDefinitionId())
                    .processDefinitionKey(processInstance.getProcessDefinitionKey())
                    .processInstanceId(processInstance.getProcessInstanceId())
                    .startTime(processInstance.getStartTime())
                    .nodeId(nodes);
        } catch (Exception e) {
            log.error("异常原因：{}", e.getMessage(), e);
        } finally {
            ActThreadLocalContext.clear();
        }
        return null;
    }

    @Override
    public void suspendProcessInstanceById(String processInstanceId) {
        runtimeService.suspendProcessInstanceById(processInstanceId);
    }

    @Override
    public void activateProcessInstanceById(String processInstanceId) {
        runtimeService.activateProcessInstanceById(processInstanceId);
    }

    @Override
    public void deleteProcessInstances(String executionId, String reason) {
        runtimeService.deleteProcessInstance(executionId, reason);
    }


    private void getInitialFlowElement() {
        BpmnModel model = deploymentService.getBpmnModel("Process_1:1:bd29ea34-8338-11eb-9bf8-0c541597bb97");
        //获取所有节点
        Process mainProcess = model.getMainProcess();
        //获取初始节点
        FlowElement element = mainProcess.getInitialFlowElement();
        FlowNode    start   = (FlowNode) element;
        //获取下一个节点
        List<SequenceFlow> outgoingFlows = start.getOutgoingFlows();
        for (SequenceFlow outgoingFlow : outgoingFlows) {
            FlowElement flowElement = outgoingFlow.getTargetFlowElement();
            System.out.println("====================下一个节点id:" + flowElement.getId());
        }
    }


}
